package com.wx.util;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * @BelongsProject: jianzhu04-0723
 * @BelongsPackage: Servlet
 * @Author: zd
 * @CreateTime: 2020-07-24 16:15
 * @Description:
 */
@WebServlet("/code")
public class Code extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        创建空白图片
        BufferedImage image = new BufferedImage(80, 30, BufferedImage.TYPE_INT_RGB);
//        获取图片画笔
        Graphics g = image.getGraphics();
        Random r = new Random();//随机数
        r.nextInt(255);//随机数0-255间
//        设置笔画
//        设置背景颜色三个参数
        g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
//        绘制矩形背景
        g.fillRect(0, 0, 100, 30);

//        调用之定义方法获取长度为5的字母数字组合字符串
        String number = getNumber(4);
        req.getSession().setAttribute("code", number);
        g.setColor(new Color(0, 0, 0));
        g.setFont(new Font("宋体", Font.BOLD, 24));
//        设置颜色字体后绘制字符串
        g.drawString(number, 5, 25);
//        绘制10条干扰线
        for (int i = 0; i < 5; i++) {
            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
            g.drawLine(r.nextInt(100),
                    r.nextInt(30),
                    r.nextInt(100),
                    r.nextInt(30));
//            直线参数（abxy）ab代表起点，xy代表终点
        }
        resp.setContentType("image/jpeg");
        OutputStream outputStream = resp.getOutputStream();
        ImageIO.write(image, "jpeg", outputStream);
        outputStream.close();
    }
    //字符串拼接
    private String getNumber(int size) {
//        String str = "QWERTYUPASDFGHJKLZXCVBNM";
        String str = "1";
        StringBuilder number = new StringBuilder();
        Random r = new Random();
        for (int i = 0; i < size; i++) {
            number.append(str.charAt(r.nextInt(str.length())));
//        str.charAt拿到下标为0-str长度之间的下标，下标从0开始
        }
        return number.toString();
    }
}

